<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>订单历史</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body { font-family: Arial, sans-serif; background:#0b132b; color:#e0e0e0; }
    header { padding:16px; background:#1c2541; }
    .container { padding:16px; }
    select, input, button { padding:8px; border-radius:6px; border:1px solid #3a506b; background:#0b132b; color:#e0e0e0; }
    button { background:#5bc0be; color:#0b132b; font-weight:700; cursor:pointer; }
    table { width:100%; border-collapse:collapse; margin-top:12px; table-layout: fixed; }
    th, td { border:1px solid #3a506b; padding:8px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    th { background:#1c2541; }
    .code { font-family: Consolas, monospace; }
    .tag { padding:2px 6px; border-radius:4px; background:#3a506b; color:#fff; font-size:12px; }
    .cols { width:100%; }
    .cols col:nth-child(1) { width:18%; }
    .cols col:nth-child(2) { width:24%; }
    .cols col:nth-child(3) { width:10%; }
    .cols col:nth-child(4) { width:12%; }
    .cols col:nth-child(5) { width:12%; }
    .cols col:nth-child(6) { width:12%; }
    .cols col:nth-child(7) { width:12%; }
  </style>
</head>
<body>
  <header style="display:flex;justify-content:space-between;align-items:center;">
    <h2>订单历史</h2>
    <a href="/api/quant/admin/home" style="color:#5bc0be;text-decoration:none;">返回首页</a>
  </header>
  <div class="container">
    <div>
      <label>选择令牌：</label>
      <select id="token"></select>
      <label>状态筛选：</label>
      <select id="status">
        <option value="">全部</option>
        <option value="pending">待派发</option>
        <option value="processing">处理中</option>
        <option value="executed">已执行</option>
        <option value="failed">失败</option>
        <option value="expired">过期</option>
      </select>
      <label>每页</label>
      <select id="pageSize">
        <option value="10">10</option>
        <option value="20" selected>20</option>
        <option value="50">50</option>
      </select>
      <label>清理天数：</label>
      <input id="days" type="number" min="1" value="30" style="width:90px" />
      <button onclick="purgeCompleted()" style="background:#ef4444;color:#fff">清空已完成</button>
      <button onclick="purgeAll()" style="background:#b91c1c;color:#fff">清空全部</button>
      <button onclick="updateDict()">更新股票字典（迈瑞）</button>
      <button onclick="goFirst()">首页</button>
      <button onclick="prevPage()">上一页</button>
      <button onclick="nextPage()">下一页</button>
      <span id="pager"></span>
    </div>
    <table>
      <colgroup class="cols"><col/><col/><col/><col/><col/><col/><col/></colgroup>
      <thead>
        <tr>
          <th>时间</th>
          <th>股票</th>
          <th>方向</th>
          <th>数量</th>
          <th>状态</th>
          <th>处理时间</th>
          <th>确认时间</th>
        </tr>
      </thead>
      <tbody id="list"></tbody>
    </table>
  </div>
  <script>
    let STOCK_DICT = {};
    async function loadStockDict(){
      try{
        const r = await fetch('/api/quant/admin/stocks/dict');
        if(r.ok){ STOCK_DICT = await r.json(); }
      }catch(e){ STOCK_DICT = {}; }
    }
    let currentPage = 1;
    let totalPages = 1;
    async function loadTokens(){
      const r = await fetch('/api/quant/admin/tokens');
      const j = await r.json();
      const sel = document.getElementById('token');
      sel.innerHTML = '';
      (j.items||[]).filter(x=>x.active).forEach(item => {
        const o = document.createElement('option');
        o.value = item.id; o.textContent = `${item.remark} (${item.token.slice(0,8)}...)`;
        sel.appendChild(o);
      });
    }
    function nameByCode(code){
      if(!code) return '';
      const k = String(code).slice(0,6);
      return STOCK_DICT[k]||'';
    }
    function fmtTime(s){
      if(!s) return '';
      const d = new Date(s);
      const pad = (n)=>String(n).padStart(2,'0');
      const ms = String(d.getMilliseconds()).padStart(3,'0');
      return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`;
    }
    function findName(item){
      const codeKey = (item.code||'').slice(0,6);
      let nm = STOCK_DICT[codeKey];
      if(!nm){
        const r = item.raw||{};
        nm = r.securityName || r.name || r.stock_name || r['A股简称'] || r['证券简称'] || '';
      }
      return nm || '未知';
    }
    function formatStock(code, exch, item){
      const nm = findName(item);
      const tag = exch?`<span class="tag">${exch}</span>`:'';
      const codeHtml = `<span class="code">${code}</span>`;
      return `${codeHtml} ${tag} ${nm?`- ${nm}`:''}`;
    }
    async function loadOrders(){
      const tok = document.getElementById('token').value;
      const status = document.getElementById('status').value;
      const url = new URL('/api/quant/admin/orders/data', window.location.origin);
      url.searchParams.set('token_id', tok);
      if(status) url.searchParams.set('status', status);
      url.searchParams.set('page', currentPage);
      const ps = parseInt(document.getElementById('pageSize') ? document.getElementById('pageSize').value : '20');
      url.searchParams.set('page_size', ps);
      const r = await fetch(url.toString());
      const j = await r.json();
      const tbody = document.getElementById('list');
      tbody.innerHTML = '';
      (j.items||[]).forEach(item => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${fmtTime(item.order_timestamp || item.created_at)}</td>
          <td>${formatStock(item.code, item.exchange, item)}</td>
          <td>${item.side||''}</td>
          <td>${item.volume??''}</td>
          <td>${item.status}</td>
          <td>${fmtTime(item.processed_time)||''}</td>
          <td>${fmtTime(item.confirmed_time)||''}</td>
        `;
        tbody.appendChild(tr);
      });
      totalPages = j.pages||1;
      document.getElementById('pager').textContent = `第 ${j.page} / ${totalPages} 页，共 ${j.total} 条`;
    }
    async function updateDict(){
      const r = await fetch('/api/quant/admin/stocks/update_all', { method:'POST' });
      if(r.ok){ await loadStockDict(); alert('字典已更新'); loadOrders(); } else { alert('更新失败'); }
    }
    
    async function purgeCompleted(){
      const tok = document.getElementById('token').value;
      const days = parseInt(document.getElementById('days').value||'0');
      if(!tok){ alert('请选择令牌'); return; }
      if(!confirm('清空该令牌下已完成订单，按天数过滤？')) return;
      const r = await fetch('/api/quant/admin/orders/purge', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ token_id: parseInt(tok), older_than_days: days, status: 'completed' }) });
      const j = await r.json();
      alert(`已删除 ${j.deleted||0} 条`);
      loadOrders();
    }
    async function purgeAll(){
      const tok = document.getElementById('token').value;
      if(!tok){ alert('请选择令牌'); return; }
      if(!confirm('确认清空该令牌下所有订单？此操作不可恢复')) return;
      const r = await fetch('/api/quant/admin/orders/purge', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ token_id: parseInt(tok), all: true }) });
      const j = await r.json();
      alert(`已删除 ${j.deleted||0} 条`);
      loadOrders();
    }
    function nextPage(){ if(currentPage<totalPages){ currentPage += 1; loadOrders(); } }
    function prevPage(){ if(currentPage>1) currentPage -= 1; loadOrders(); }
    function goFirst(){ currentPage = 1; loadOrders(); }
    document.getElementById('status').addEventListener('change', ()=>{ currentPage=1; loadOrders(); });
    const psEl = document.createElement('div');
    document.getElementById('pageSize')?.addEventListener('change', ()=>{ currentPage=1; loadOrders(); });
    document.addEventListener('DOMContentLoaded', async () => {
      await loadStockDict();
      await loadTokens();
      currentPage = 1;
      loadOrders();
    });
    document.getElementById('token').addEventListener('change', ()=>{ currentPage=1; loadOrders(); });
  </script>
</body>
</html>